import { ModdleElement } from 'bpmn-moddle'
import { getBusinessObject, is } from 'bpmn-js/lib/util/ModelUtil'
import { useSettingStore } from '@/store/bpmnProcess/settingStore'
import { useModelerStore } from '@/store/bpmnProcess/modelerStore'
import { getServiceTaskLikeBusinessObject } from './bpmnPropertyUtils/eventDefinition'

export function isExternalTask(element): boolean {
  const businessObject = getBusinessObject(element)
  return is(element, 'bpmn:Process') || (is(element, 'bpmn:Participant') && businessObject.get('processRef')) || isExternalTaskLike(element)
}

// 任务优先级
export function getExternalTaskValue(element): string | undefined {
  const prefix = useSettingStore().editor.processEngine
  const businessObject = getRelativeBusinessObject(element)
  return businessObject.get(`${prefix}:taskPriority`)
}
export function setExternalTaskValue(element, value: string | undefined) {
  const prefix = useSettingStore().editor.processEngine
  const modeling = useModelerStore().getModeling
  const businessObject = getRelativeBusinessObject(element)
  modeling.updateModdleProperties(element, businessObject, {
    [`${prefix}:taskPriority`]: value
  })
}

// ///////// helpers
function isExternalTaskLike(element): boolean {
  const prefix = useSettingStore().editor.processEngine
  const bo = getServiceTaskLikeBusinessObject(element)
  const type = bo && bo.get(`${prefix}:type`)
  return bo && is(bo, `${prefix}:ServiceTaskLike`) && type && type === 'external'
}

function getRelativeBusinessObject(element): ModdleElement {
  let businessObject
  if (is(element, 'bpmn:Participant')) {
    businessObject = getBusinessObject(element).get('processRef')
  } else if (isExternalTaskLike(element)) {
    businessObject = getServiceTaskLikeBusinessObject(element)
  } else {
    businessObject = getBusinessObject(element)
  }
  return businessObject
}
